package competition.dao.impl;

import competition.BaseDao;
import competition.dao.UserDao;
import competition.po.*;
import competition.vo.AreaName;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.hibernate.query.Query;
import org.springframework.stereotype.Repository;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2017/8/7/007.
 */
@Repository("userDao")
public class UserDaoImpl extends BaseDao implements UserDao {
    /**
     * 001.判断用户是否存在
     *
     * @param username
     * @return
     */
    public Map isExist(String username) {
        Session session = getCurrentSession();
        Transaction transaction = session.beginTransaction();
        Criteria criteria = session.createCriteria(TUsersEntity.class);
        Criterion criterion = Restrictions.eq("username", username);
        criteria.add(criterion);
        List<TUsersEntity> list = criteria.list();
        Map map = new HashMap();
        if (list.size() == 0) {
            map.put("isExist", "false");
            return map;
        } else {
            map.put("isExist", "true");
            map.put("object", list);
            return map;
        }
    }

    /**
     * 002.注册数据
     *
     * @param username
     * @param password
     * @param name
     * @return
     */
    public Map insertData(String username, String password, String name) {
        Session session = getCurrentSession();
        Transaction transaction = session.beginTransaction();
        TUsersEntity tUsersEntity = new TUsersEntity();
        tUsersEntity.setUsername(username);
        tUsersEntity.setPassword(password);
        tUsersEntity.setName(name);
        tUsersEntity.setRepuation(0.0);
        tUsersEntity.setMoney(new BigDecimal(0));
        tUsersEntity.setIcon("upload//demo//user.jpg");
        Map map = new HashMap();
        try {
            session.save(tUsersEntity);
            transaction.commit();
            map.put("insert", "true");
            return map;
        } catch (Exception e) {
            transaction.rollback();
        }
        map.put("insert", "false");
        return map;
    }

    /**
     * 003.修改密码
     *
     * @param username
     * @param newPassword
     * @return
     */
    public Map modify(String username, String newPassword) {
        Session session = getCurrentSession();
        Transaction transaction = session.beginTransaction();
        Criteria criteria = session.createCriteria(TUsersEntity.class);
        Criterion criterion = Restrictions.eq("username", username);
        criteria.add(criterion);
        List<TUsersEntity> list = criteria.list();
        TUsersEntity tUsersEntity = session.load(TUsersEntity.class, list.get(0).getId());
        tUsersEntity.setPassword(newPassword);
        Map map = new HashMap();
        try {
            session.update(tUsersEntity);
            transaction.commit();
            map.put("setting", "true");
            return map;
        } catch (Exception e) {
            transaction.rollback();
            map.put("setting", "false");
        }
        return map;
    }

    public int consumeTimes(int user_id) {
        Session session = getCurrentSession();
        Transaction transaction = session.beginTransaction();
        Criteria criteria = session.createCriteria(TUsersRecordEntity.class);
        Criterion criterion = Restrictions.eq("userId", user_id);
        criteria.add(criterion);
        int times = criteria.list().size();
        return times;
    }

    public List personMessage(int user_id) {
        Session session = getCurrentSession();
        Transaction transaction = session.beginTransaction();
        Criteria criteria = session.createCriteria(TUsersEntity.class);
        Criterion criterion = Restrictions.eq("id", user_id);
        criteria.add(criterion);
        List<TUsersEntity> list = criteria.list();
        list.get(0).setIcon(AreaName.name + list.get(0).getIcon());
        return list;
    }

    public List queryHadPublishTrade() {
        Session session = getCurrentSession();
        Transaction transaction = session.beginTransaction();
        String sql = "select name,icon,count(*) as rank from VUserRankEntity GROUP BY username,name,icon ORDER BY rank desc";
        List<VUserRankEntity> list = session.createQuery(sql).list();

//        Criteria criteria=session.createCriteria(VUserRankEntity.class);
//        criteria.setProjection(Projections.groupProperty("username"));
//        List<VUserRankEntity>list=criteria.list();

        return list;
    }

    public boolean uploadIcon(String img, int user_id) {
        Session session = getCurrentSession();
        Transaction transaction = session.beginTransaction();
        TUsersEntity tUsersEntity = session.load(TUsersEntity.class, user_id);
        tUsersEntity.setIcon(img);
        try {
            session.update(tUsersEntity);
            transaction.commit();
            return true;
        } catch (Exception e) {
            transaction.rollback();
        }
        return false;
    }

    public boolean focusTop(int user_id, int top_id, int status) {
        Session session = getCurrentSession();
        Transaction transaction = session.beginTransaction();
        Criteria criteria = session.createCriteria(TFocusTopEntity.class);
        Criterion c1 = Restrictions.eq("userId", user_id);
        Criterion c2 = Restrictions.eq("focusId", top_id);
        criteria.add(c1);
        criteria.add(c2);
        List<TFocusTopEntity> list = criteria.list();

        if (status == 1) {
            if (list.size() == 1) {
                return false;
            }
            TFocusTopEntity tFocusTopEntity = new TFocusTopEntity();
            tFocusTopEntity.setFocusId(top_id);
            tFocusTopEntity.setUserId(user_id);
            try {
                session.save(tFocusTopEntity);
                transaction.commit();
                return true;
            } catch (Exception e) {
                transaction.rollback();
            }
            return false;
        } else {

            if (list.size() == 0) {
                return false;
            } else {
                TFocusTopEntity tFocusTopEntity = session.load(TFocusTopEntity.class, list.get(0).getId());
                try {
                    session.delete(tFocusTopEntity);
                    transaction.commit();
                    return true;

                } catch (Exception e) {
                    transaction.rollback();
                }
                return false;
            }
        }
    }

    public boolean focusTrade(int user_id, int trade_id, int status) {
        Session session = getCurrentSession();
        Transaction transaction = session.beginTransaction();
        Criteria criteria = session.createCriteria(TFocusTradeEntity.class);
        Criterion c1 = Restrictions.eq("userId", user_id);
        Criterion c2 = Restrictions.eq("focusId", trade_id);
        criteria.add(c1);
        criteria.add(c2);
        List<TFocusTradeEntity> list = criteria.list();

        if (status == 1) {
            if (list.size() == 1) {
                return false;
            }
            TFocusTradeEntity tFocusTradeEntity = new TFocusTradeEntity();
            tFocusTradeEntity.setFocusId(trade_id);
            tFocusTradeEntity.setUserId(user_id);
            try {
                session.save(tFocusTradeEntity);
                transaction.commit();
                return true;
            } catch (Exception e) {
                transaction.rollback();
            }
            return false;
        } else {

            if (list.size() == 0) {
                return false;
            } else {
                TFocusTradeEntity tFocusTradeEntity = session.load(TFocusTradeEntity.class, list.get(0).getId());
                try {
                    session.delete(tFocusTradeEntity);
                    transaction.commit();
                    return true;

                } catch (Exception e) {
                    transaction.rollback();
                }
                return false;
            }
        }
    }

    public Map lookFocus(int user_id, int page, int num) {
        Session session = getCurrentSession();
        Transaction transaction = session.beginTransaction();
        String sql = "";
        Criteria criteria = session.createCriteria(VUserFollowEntity.class).setFirstResult((page - 1) * num).setMaxResults(num);
        Criterion criterion = Restrictions.eq("userId", user_id);
        criteria.add(criterion);
        List<VUserFollowEntity> list = criteria.list();
        for (int i = 0; i < list.size(); i++) {
            list.get(i).setIcon(AreaName.name + list.get(i).getIcon());
        }
        Map map=new HashMap();
        map.put("result",list);
        map.put("length",list.size());


        map.put("status",200);

        return map;

    }

    public boolean userFollow(int user_id, int follow_id, int status) {
        Session session = getCurrentSession();
        Transaction transaction = session.beginTransaction();
        Criteria criteria = session.createCriteria(TUsersFollowEntity.class);
        Criterion c1 = Restrictions.eq("userId", user_id);
        Criterion c2 = Restrictions.eq("followId", follow_id);
        criteria.add(c1);
        criteria.add(c2);
        List<TUsersFollowEntity> list = criteria.list();

        if (status == 1) {
            if (list.size() == 1) {
                return false;
            }
            TUsersFollowEntity tUsersFollowEntity = new TUsersFollowEntity();
            tUsersFollowEntity.setFollowId(follow_id);
            tUsersFollowEntity.setUserId(user_id);
            try {
                session.save(tUsersFollowEntity);
                transaction.commit();
                return true;
            } catch (Exception e) {
                transaction.rollback();
            }
            return false;
        } else {

            if (list.size() == 0) {
                return false;
            } else {
                TUsersFollowEntity tUsersFollowEntity = session.load(TUsersFollowEntity.class, list.get(0).getId());
                try {
                    session.delete(tUsersFollowEntity);
                    transaction.commit();
                    return true;

                } catch (Exception e) {
                    transaction.rollback();
                }
                return false;
            }
        }
    }

    public int lookFollow(int user_id) {
        Session session = getCurrentSession();
        Transaction transaction = session.beginTransaction();
        Criteria criteria = session.createCriteria(VUserFollowEntity.class);
        Criterion criterion = Restrictions.eq("userId", user_id);
        criteria.add(criterion);
        List<VUserFollowEntity> list = criteria.list();
        return list.size();
    }

    public Map lookSelfFocus(int user_id, int page, int num) {
        Session session = getCurrentSession();
        Transaction transaction = session.beginTransaction();
        String sql = "";
        Criteria criteria = session.createCriteria(VUserSelfFollowEntity.class).setFirstResult((page - 1) * num).setMaxResults(num);
        Criterion criterion = Restrictions.eq("followId", user_id);
        criteria.add(criterion);
        List<VUserSelfFollowEntity> list = criteria.list();
        for (int i = 0; i < list.size(); i++) {
            list.get(i).setIcon(AreaName.name + list.get(i).getIcon());
        }
        Map map=new HashMap();
        map.put("result",list);
        map.put("length",list.size());


        map.put("status",200);

        return map;
    }

    public int lookSelfFollow(int user_id) {
        Session session = getCurrentSession();
        Transaction transaction = session.beginTransaction();
        Criteria criteria = session.createCriteria(VUserSelfFollowEntity.class);
        Criterion criterion = Restrictions.eq("followId", user_id);
        criteria.add(criterion);
        List<VUserSelfFollowEntity> list = criteria.list();
        return list.size();
    }

    public boolean leaveMessageUser(int username_id, int leaveName_id, String message, int is_reply) {
        Session session=getCurrentSession();
        Transaction transaction=session.beginTransaction();

        TUserMessageEntity tUserMessageEntity=new TUserMessageEntity();
        tUserMessageEntity.setUserId(username_id);
        tUserMessageEntity.setLeaveId(leaveName_id);
        tUserMessageEntity.setIsReply(is_reply);
        tUserMessageEntity.setMessage(message);

        Date dNow = new Date();
        SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        tUserMessageEntity.setCreateTime(ft.format(dNow).toString());

        try {
            session.save(tUserMessageEntity);
            transaction.commit();
            return true;
        }catch (Exception e){
            transaction.rollback();
        }
        return false;
    }

    public List lookMessageUser(int user_id) {

        Session session=getCurrentSession();
        Transaction transaction=session.beginTransaction();
        Order order=Order.desc("createTime");
        Criteria criteria=session.createCriteria(VUserMessageEntity.class).addOrder(order);
        Criterion criterion=Restrictions.eq("userId",user_id);
        criteria.add(criterion);
        List<VUserMessageEntity>list=criteria.list();
        for(int i=0;i<list.size();i++){
            list.get(i).setIcon(AreaName.name+list.get(i).getIcon());
        }

        return list;
    }

    public List getNews(int page,int num) {
        Session session=getCurrentSession();
        Transaction transaction=session.beginTransaction();

        Criteria criteria=session.createCriteria(TNewsEntity.class).setMaxResults(num).setFirstResult((page-1)*num);
        Order order=Order.desc("publishTime");
        List <TNewsEntity>list=criteria.addOrder(order).list();
        for(int i=0;i<list.size();i++){
            list.get(i).setPicture(AreaName.name+list.get(i).getPicture());
        }
        return list;
    }

    public List getTop(int user_id) {
        Session session=getCurrentSession();
        Transaction transaction=session.beginTransaction();
        Criteria criteria=session.createCriteria(VFocusTopDetailEntity.class);
        Criterion criterion=Restrictions.eq("userId",user_id);
        criteria.add(criterion);
        List<VFocusTopDetailEntity>list=criteria.list();
        for(int i=0;i<list.size();i++){
            list.get(i).setIcon(AreaName.name+list.get(i).getIcon());
        }
        return list;

    }
}
